<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="概述 堆排序即是利用堆这个数据结构来完成排序的.所以,要想理解堆排序就要先了解堆. 堆 堆(Heap)是一种数据结构,它可以被看做是一棵树的数组对象.一个二叉堆拥有以下性质.  父节点k的左子节点在数组中的索引位置为2 * k + 1.   父节点k的右子节点在数组中的索引位置为2 * k + 2.   子节点i的父节点在数组中的索引位置为(i - 1) &#x2F; 2.   父节点k的任意子节点都必须小">
<meta property="og:type" content="article">
<meta property="og:title" content="深入浅出排序算法(1)-堆排序">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/09/2017-06-09-sort_algorithms_heapSort/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="概述 堆排序即是利用堆这个数据结构来完成排序的.所以,要想理解堆排序就要先了解堆. 堆 堆(Heap)是一种数据结构,它可以被看做是一棵树的数组对象.一个二叉堆拥有以下性质.  父节点k的左子节点在数组中的索引位置为2 * k + 1.   父节点k的右子节点在数组中的索引位置为2 * k + 2.   子节点i的父节点在数组中的索引位置为(i - 1) &#x2F; 2.   父节点k的任意子节点都必须小">
<meta property="og:locale">
<meta property="article:published_time" content="2017-06-09T10:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="2017">
<meta property="article:tag" content="排序算法">
<meta property="article:tag" content="Algorithms">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/09/2017-06-09-sort_algorithms_heapSort/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>深入浅出排序算法(1)-堆排序 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A0%86"><span class="nav-number">2.</span> <span class="nav-text">堆</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%9C%80%E5%A4%A7%E5%A0%86%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.1.</span> <span class="nav-text">最大堆代码实现</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%98%E5%85%88%E9%98%9F%E5%88%97"><span class="nav-number">3.</span> <span class="nav-text">优先队列</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B7%BB%E5%8A%A0"><span class="nav-number">3.1.</span> <span class="nav-text">添加</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%A0%E9%99%A4"><span class="nav-number">3.2.</span> <span class="nav-text">删除</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A0%86%E6%8E%92%E5%BA%8F"><span class="nav-number">4.</span> <span class="nav-text">堆排序</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%9B%B4%E6%8E%A5%E4%BD%BF%E7%94%A8%E5%A0%86%E5%AE%9E%E7%8E%B0%E5%A0%86%E6%8E%92%E5%BA%8F"><span class="nav-number">4.1.</span> <span class="nav-text">直接使用堆实现堆排序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E4%BC%98%E5%85%88%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E5%A0%86%E6%8E%92%E5%BA%8F"><span class="nav-number">4.2.</span> <span class="nav-text">使用优先队列实现堆排序</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/09/2017-06-09-sort_algorithms_heapSort/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入浅出排序算法(1)-堆排序
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-06-09 18:00:00" itemprop="dateCreated datePublished" datetime="2017-06-09T18:00:00+08:00">2017-06-09</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">排序算法</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><hr>
<p><code>堆排序</code>即是利用<code>堆</code>这个数据结构来完成排序的.所以,要想理解<code>堆排序</code>就要先了解<code>堆</code>.</p>
<h3 id="堆"><a href="#堆" class="headerlink" title="堆"></a>堆</h3><hr>
<p><code>堆(Heap)</code>是一种数据结构,它可以被看做是一棵树的数组对象.一个<code>二叉堆</code>拥有以下性质.</p>
<ul>
<li>父节点<code>k</code>的左子节点在数组中的索引位置为<code>2 * k + 1</code>.</li>
</ul>
<ul>
<li>父节点<code>k</code>的右子节点在数组中的索引位置为<code>2 * k + 2</code>.</li>
</ul>
<ul>
<li>子节点<code>i</code>的父节点在数组中的索引位置为<code>(i - 1) / 2</code>.</li>
</ul>
<ul>
<li>父节点<code>k</code>的任意子节点都必须小于(或大于)<code>k</code>.</li>
</ul>
<ul>
<li>根节点必须是最大节点(或最小节点).</li>
</ul>
<h4 id="最大堆代码实现"><a href="#最大堆代码实现" class="headerlink" title="最大堆代码实现"></a>最大堆代码实现</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MaxHeap</span>&lt;<span class="title">T</span> <span class="keyword">extends</span> <span class="title">Comparable</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    T[] heap;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">MaxHeap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MaxHeap</span><span class="params">(T[] heap)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.heap = heap;</span><br><span class="line">        buildHeap();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 自底向上构建堆</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">buildHeap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> length = heap.length;</span><br><span class="line">        <span class="comment">// 当堆为空或者长度为1时不需要任何操作</span></span><br><span class="line">        <span class="keyword">if</span> (length &lt;= <span class="number">1</span>)</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> root = (length - <span class="number">2</span>) &gt;&gt;&gt; <span class="number">1</span>; <span class="comment">// (i - 1) / 2</span></span><br><span class="line">        <span class="keyword">while</span> (root &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">            heapify(heap, length, root);</span><br><span class="line">            root--;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 调整堆的结构</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> heap   堆</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> length 堆的长度</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> root   根节点索引</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">heapify</span><span class="params">(T[] heap, <span class="keyword">int</span> length, <span class="keyword">int</span> root)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (root &gt;= length)</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> largest = root; <span class="comment">// 表示root,left,right中最大值的变量</span></span><br><span class="line">        <span class="keyword">int</span> left = (root &lt;&lt; <span class="number">1</span>) + <span class="number">1</span>; <span class="comment">// 左子节点,root * 2 + 1</span></span><br><span class="line">        <span class="keyword">int</span> right = left + <span class="number">1</span>; <span class="comment">// 右子节点,root * 2 + 2</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 找出最大值</span></span><br><span class="line">        <span class="keyword">if</span> (left &lt; length &amp;&amp; greater(heap[left], heap[largest]))</span><br><span class="line">            largest = left;</span><br><span class="line">        <span class="keyword">if</span> (right &lt; length &amp;&amp; greater(heap[right], heap[largest]))</span><br><span class="line">            largest = right;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 如果largest发生变化,将largest与root交换</span></span><br><span class="line">        <span class="keyword">if</span> (largest != root) &#123;</span><br><span class="line">            T t = heap[root];</span><br><span class="line">            heap[root] = heap[largest];</span><br><span class="line">            heap[largest] = t;</span><br><span class="line">            <span class="comment">// 继续向下调整堆</span></span><br><span class="line">            heapify(heap, length, largest);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">greater</span><span class="params">(Comparable a, Comparable b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a.compareTo(b) &gt; <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="优先队列"><a href="#优先队列" class="headerlink" title="优先队列"></a>优先队列</h3><hr>
<p>普通的队列是基于<code>先进先出</code>的,也就是说最先入队的元素永远是在第一位,而<code>优先队列</code>中的每一个元素都是拥有<code>优先级</code>的,<code>优先级</code>最高的元素永远在第一位.</p>
<p><code>优先队列</code>也是<code>贪心算法</code>的体现,所谓的<code>贪心算法</code>即是在问题求解的每一步中总是选择当前最好的结果.</p>
<p><code>堆</code>就是用于实现<code>优先队列</code>的,因为<code>堆</code>的性质与<code>优先队列</code>十分吻合.</p>
<h4 id="添加"><a href="#添加" class="headerlink" title="添加"></a>添加</h4><hr>
<p>往<code>优先队列</code>中添加元素时,我们只需要将元素添加到数组末尾并调整堆(以下例子均是以最大堆为例).</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">if</span> (t == <span class="keyword">null</span>)</span><br><span class="line">           <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">       <span class="keyword">if</span> (size == queue.length)</span><br><span class="line">           resize(queue.length * <span class="number">2</span>);</span><br><span class="line">       <span class="keyword">int</span> i = size;</span><br><span class="line">	<span class="comment">// 如果当前队列为空,则不需要进行堆调整直接插入元素即可</span></span><br><span class="line">       <span class="keyword">if</span> (i == <span class="number">0</span>)</span><br><span class="line">           queue[<span class="number">0</span>] = t;</span><br><span class="line">       <span class="keyword">else</span></span><br><span class="line">           swim(i, t);</span><br><span class="line">       size++;</span><br><span class="line">       <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 上浮调整</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">swim</span><span class="params">(<span class="keyword">int</span> i, T t)</span> </span>&#123;</span><br><span class="line">       Comparable&lt;? <span class="keyword">super</span> T&gt; key = (Comparable) t;</span><br><span class="line">       <span class="keyword">while</span> (i &gt; <span class="number">0</span>) &#123;</span><br><span class="line">           <span class="keyword">int</span> parent = (i - <span class="number">1</span>) &gt;&gt;&gt; <span class="number">1</span>;</span><br><span class="line">           T p = (T) queue[parent];</span><br><span class="line">		<span class="comment">// 如果key小于他的父节点(符合最大堆规则)则结束调整</span></span><br><span class="line">           <span class="keyword">if</span> (key.compareTo(p) &lt; <span class="number">0</span>)</span><br><span class="line">               <span class="keyword">break</span>;</span><br><span class="line">           queue[i] = p;</span><br><span class="line">           i = parent;</span><br><span class="line">       &#125;</span><br><span class="line">       queue[i] = key;</span><br><span class="line">   &#125;	</span><br></pre></td></tr></table></figure>
<h4 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h4><hr>
<p>删除操作要稍微麻烦一点,将<code>优先队列</code>中末尾的元素放到队头并进行堆调整.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> T <span class="title">poll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       <span class="keyword">if</span> (isEmpty())</span><br><span class="line">           <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">int</span> s = --size;</span><br><span class="line">       Object result = queue[<span class="number">0</span>];</span><br><span class="line">       Object end = queue[s];</span><br><span class="line">       queue[s] = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">if</span> (s != <span class="number">0</span>)</span><br><span class="line">           sink(<span class="number">0</span>, (T) end);</span><br><span class="line">       <span class="keyword">if</span> (size &lt;= queue.length / <span class="number">4</span>)</span><br><span class="line">           resize(queue.length / <span class="number">2</span>);</span><br><span class="line">       <span class="keyword">return</span> (T) result;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 下沉调整</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">sink</span><span class="params">(<span class="keyword">int</span> i, T t)</span> </span>&#123;</span><br><span class="line">       Comparable&lt;? <span class="keyword">super</span> T&gt; key = (Comparable&lt;? <span class="keyword">super</span> T&gt;) t;</span><br><span class="line">       <span class="keyword">int</span> half = size &gt;&gt;&gt; <span class="number">1</span>;</span><br><span class="line">       <span class="keyword">while</span> (i &lt; half) &#123;</span><br><span class="line">           <span class="keyword">int</span> child = (i &lt;&lt; <span class="number">1</span>) + <span class="number">1</span>; <span class="comment">// 左子节点</span></span><br><span class="line">           <span class="keyword">int</span> right = child + <span class="number">1</span>; <span class="comment">// 右子节点</span></span><br><span class="line">           T max = (T) queue[child];</span><br><span class="line">           <span class="comment">// find maximum element</span></span><br><span class="line">           <span class="keyword">if</span> (right &lt; size &amp;&amp;</span><br><span class="line">                   ((Comparable&lt;? <span class="keyword">super</span> T&gt;) max).compareTo((T) queue[right]) &lt; <span class="number">0</span>)</span><br><span class="line">               max = (T) queue[child = right];</span><br><span class="line">		<span class="comment">// key大于它的最大子节点(符合最大堆规则)则结束调整	</span></span><br><span class="line">           <span class="keyword">if</span> (key.compareTo(max) &gt; <span class="number">0</span>)</span><br><span class="line">               <span class="keyword">break</span>;</span><br><span class="line">           queue[i] = max;</span><br><span class="line">           i = child;</span><br><span class="line">       &#125;</span><br><span class="line">       queue[i] = key;</span><br><span class="line">   &#125;	</span><br></pre></td></tr></table></figure>
<p><a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/test-demo/blob/master/src/main/java/com/sun/sylvanas/data_struct/heap/MaxPriorityQueue.java">点击查看优先队列完整代码</a></p>
<h3 id="堆排序"><a href="#堆排序" class="headerlink" title="堆排序"></a>堆排序</h3><hr>
<p>实现<code>堆排序</code>有两种方法,一种是使用<code>优先队列</code>,另一种是直接使用<code>堆</code>.</p>
<h4 id="直接使用堆实现堆排序"><a href="#直接使用堆实现堆排序" class="headerlink" title="直接使用堆实现堆排序"></a>直接使用堆实现堆排序</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用最大堆实现堆排序</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">maxHeapSort</span><span class="params">(Comparable[] a)</span> </span>&#123;</span><br><span class="line">    MaxHeap&lt;Comparable&gt; maxHeap = <span class="keyword">new</span> MaxHeap&lt;&gt;(a);</span><br><span class="line">    <span class="comment">//不断地将最大堆中顶端元素(最大值)与最底部的元素(最小值)交换</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = a.length - <span class="number">1</span>; i &gt; <span class="number">0</span>; i--) &#123;</span><br><span class="line">        Comparable largest = a[<span class="number">0</span>];</span><br><span class="line">        a[<span class="number">0</span>] = a[i];</span><br><span class="line">        a[i] = largest;</span><br><span class="line">        <span class="comment">// 堆减少,并调整新的堆</span></span><br><span class="line">        maxHeap.heapify(a, i, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="使用优先队列实现堆排序"><a href="#使用优先队列实现堆排序" class="headerlink" title="使用优先队列实现堆排序"></a>使用优先队列实现堆排序</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用优先队列实现堆排序</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">pqSort</span><span class="params">(Comparable[] a)</span> </span>&#123;</span><br><span class="line">    MinPriorityQueue&lt;Comparable&gt; priorityQueue = <span class="keyword">new</span> MinPriorityQueue&lt;&gt;();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a.length; i++) &#123;</span><br><span class="line">        priorityQueue.add(a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a.length; i++) &#123;</span><br><span class="line">        a[i] = priorityQueue.poll();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/2017/" rel="tag"># 2017</a>
              <a href="/yuwanzi.io/tags/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/" rel="tag"># 排序算法</a>
              <a href="/yuwanzi.io/tags/Algorithms/" rel="tag"># Algorithms</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/06/07/2017-06-07-IoC&AOP/" rel="prev" title="IoC与AOP的那点事儿">
                  <i class="fa fa-chevron-left"></i> IoC与AOP的那点事儿
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/06/12/2017-06-12-sort_algorithmes_mergeSort/" rel="next" title="深入浅出排序算法(2)-归并排序">
                  深入浅出排序算法(2)-归并排序 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
